﻿using AutoMapper;
using Management.Systeam.Domaina;
using Management.Systeam.ErrorCode;
using Management.Systeam.Infrastructure.Interface;
using Management.Systeam.Write.Api.Application.Command.Useres;
using MediatR;

namespace Management.Systeam.Write.Api.Application.CommandHandler.Useres
{
    public class AddUserCommandHandler : IRequestHandler<AddUserCommand, ApiResult<int>>
    {
        IBaseRepository<Users> Users;
        IMapper mapper;
        ILogger<AddUserCommandHandler> logger;
        public AddUserCommandHandler(IBaseRepository<Users> Users, IMapper mapper, ILogger<AddUserCommandHandler> logger)
        {
            this.Users = Users;
            this.mapper = mapper;
            this.logger = logger;
        }

        public async Task<ApiResult<int>> Handle(AddUserCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> apiResult = new ApiResult<int>();
            try
            {
                var model = mapper.Map<Users>(request);
                model.CreateTime = DateTime.Now;
                int Ccout = Users.InsertAsync(model).Result;
                if (Ccout > 0)
                {
                    apiResult.Code = ApiEnum.success;
                    apiResult.Message = "添加成功";
                    apiResult.Data = 1;
                }
                else
                {
                    apiResult.Code = ApiEnum.error;
                    apiResult.Message = "添加失败";
                    apiResult.Data = 0;
                }

            }
            catch (Exception ex)
            {
              
                apiResult.Code = ApiEnum.error;
                apiResult.Message = ex.Message;
                logger.LogError(ex, "添加信息异常");
                throw;

            }
            return apiResult;
        }
    }
}
